<!DOCTYPE html>
<html lang="zh-CN">
  <head>
  <meta charset="UTF-8">
  <meta 
    name="viewport"
    content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
  <meta 
    http-equiv="X-UA-Compatible" 
    content="ie=edge">
  <meta 
    name="theme-color" 
    content="#fff" 
    id="theme-color">
  <meta 
    name="description" 
    content="hexoDemo用于介绍如何使用hexo">
  <link 
    rel="icon" 
    href="/">
  <title>11-流程控制语句：选择结构（if和switch）</title>
  
    
      <meta 
        property="og:title" 
        content="11-流程控制语句：选择结构（if和switch）">
    
    
      <meta 
        property="og:url" 
        content="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/11-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%EF%BC%9A%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84%EF%BC%88if%E5%92%8Cswitch%EF%BC%89/index.html">
    
    
      <meta 
        property="og:img" 
        content="https://img.songhn.com/img/Y67gdd.png">
    
    
      <meta 
        property="og:img" 
        content="hexoDemo用于介绍如何使用hexo">
    
    
      <meta 
        property="og:type" 
        content="article">
      <meta 
        property="og:article:published_time" 
        content="2004-03-01">
      <meta 
        property="og:article:modified_time" 
        content="2023-03-14">
      <meta 
        property="og:article:author" 
        content="zwl5670">
      
        
          <meta 
            property="og:article:tag" 
            content="JS基础">
        
      
    
  
  
  <link rel="preload" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css" as="style" >
  <link rel="preload" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css" as="style" >
  <link rel="preload" href="/css/main.css" as="style" >
  
  <link rel="modulepreload" href="//instant.page/5.1.0">
  
  <link rel="stylesheet" href="/css/main.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1946621_i1kgafibvw.css">
  
  <link rel="stylesheet" href="//at.alicdn.com/t/font_1952792_89b4ac4k4up.css">
  
  
  
    <link rel="stylesheet" href="/js/lib/lightbox/baguetteBox.min.css">
  
  <script>
    function loadScript(url, cb) {
      var script = document.createElement('script');
      script.src = url;
      if (cb) script.onload = cb;
      script.async = true;
      document.body.appendChild(script);
    }
    function loadCSS(href, data, attr) {
      var sheet = document.createElement('link');
      sheet.ref = 'stylesheet';
      sheet.href = href;
      sheet.dataset[data] = attr;
      document.head.appendChild(sheet);
    }
    function changeCSS(cssFile, data, attr) {
      var oldlink = document.querySelector(data);
      var newlink = document.createElement("link");
      newlink.setAttribute("rel", "stylesheet");
      newlink.setAttribute("href", cssFile);
      newlink.dataset.prism = attr;
      document.head.replaceChild(newlink, oldlink);
    }
  </script>
  
    
  
  <script>
    // control reverse button
    var reverseDarkList = {
      dark: 'light',
      light: 'dark'
    };
    var themeColor = {
      dark: '#1c1c1e',
      light: '#fff'
    }
    // get the data of css prefers-color-scheme
    var getCssMediaQuery = function() {
      return window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light';
    };
    // reverse current darkmode setting function
    var reverseDarkModeSetting = function() {
      var setting = localStorage.getItem('user-color-scheme');
      if(reverseDarkList[setting]) {
        setting = reverseDarkList[setting];
      } else if(setting === null) {
        setting = reverseDarkList[getCssMediaQuery()];
      } else {
        return;
      }
      localStorage.setItem('user-color-scheme', setting);
      return setting;
    };
    // apply current darkmode setting
  </script>
  
    <script>
      var setDarkmode = function(mode) {
      var setting = mode || localStorage.getItem('user-color-scheme');
      if(setting === getCssMediaQuery()) {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else if(reverseDarkList[setting]) {
        document.documentElement.setAttribute('data-user-color-scheme', setting);
        document.getElementById('theme-color').content = themeColor[setting];
        document.getElementById('theme-color').dataset.mode = setting;
      } else {
        document.documentElement.removeAttribute('data-user-color-scheme');
        localStorage.removeItem('user-color-scheme');
        document.getElementById('theme-color').content = themeColor[getCssMediaQuery()];
        document.getElementById('theme-color').dataset.mode = getCssMediaQuery();
      }
    };
    setDarkmode();
    </script>
  
  
  
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.js" as="script">
    <link rel="preload" href="/js/lib/lightbox/baguetteBox.min.css" as="style" >
  
  
    <link rel="preload" href="/js/lib/lozad.min.js" as="script">
  
  
  
  
  
  
<meta name="generator" content="Hexo 6.3.0"></head>

  <body>
    <div class="wrapper">
       
      <nav class="navbar">
  <div class="navbar-logo">
    <a class="navbar-logo-main" href="/">
      
      <span class="navbar-logo-dsc">前端面试</span>
      </a>
  </div>
  <div class="navbar-menu">
    
      <a 
        href="/" 
        class="navbar-menu-item">
        
          首页
        
      </a>
    
      <a 
        href="/archives" 
        class="navbar-menu-item">
        
          归档
        
      </a>
    
      <a 
        href="/tags" 
        class="navbar-menu-item">
        
          标签
        
      </a>
    
      <a 
        href="/categories" 
        class="navbar-menu-item">
        
          分类
        
      </a>
    
      <a 
        href="/about" 
        class="navbar-menu-item">
        
          关于
        
      </a>
    
      <a 
        href="/links" 
        class="navbar-menu-item">
        
          友链
        
      </a>
    
    <button 
      class="navbar-menu-item darknavbar navbar-menu-btn" 
      aria-label="Toggle dark mode"
      id="dark">
      <i class="iconfont icon-weather"></i>
    </button>
    <button 
      class="navbar-menu-item searchnavbar navbar-menu-btn" 
      aria-label="Toggle search"
      id="search">
      <!-- <i 
        class="iconfont icon-search" 
        style="font-size: 1.2rem; font-weight: 400;">
      </i> -->
      <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img"
        class="iconify iconify--ion" width="28" height="28" preserveAspectRatio="xMidYMid meet" viewBox="0 0 512 512">
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M256 80a176 176 0 1 0 176 176A176 176 0 0 0 256 80Z"></path>
        <path fill="none" stroke="currentColor" stroke-miterlimit="10" stroke-width="28"
          d="M232 160a72 72 0 1 0 72 72a72 72 0 0 0-72-72Z"></path>
        <path fill="none" stroke="currentColor" stroke-linecap="round" stroke-miterlimit="10" stroke-width="28"
          d="M283.64 283.64L336 336"></path>
      </svg>
    </button>
  </div>
</nav> 
      
      <div 
        id="local-search" 
        style="display: none">
        <input
          class="navbar-menu-item"
          id="search-input"
          placeholder="请输入搜索内容..." />
        <div id="search-content"></div>
      </div>
      
      <div class="section-wrap">
        <div class="container">
          <div class="columns">
            <aside class="left-column">
              
              <div class="card card-author">
                
  <img 
    src="https://img.songhn.com/img/Y67gdd.png" 
    class="author-img"
    width="88"
    height="88"
    alt="author avatar">

<p class="author-name">zwl5670</p>
<p class="author-description">前端学习资料</p>
<div class="author-message">
  <a 
    class="author-posts-count" 
    href="/archives">
    <span>215</span>
    <span>文章</span>
  </a>
  <a 
    class="author-categories-count" 
    href="/categories">
    <span>14</span>
    <span>分类</span>
  </a>
  <a 
    class="author-tags-count" 
    href="/tags">
    <span>14</span>
    <span>标签</span>
  </a>
</div>

              </div>
               <div class="sticky-tablet">
  
  
    <article class="display-when-two-columns spacer">
      <div class="card card-content toc-card">
        <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-text">代码块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5"><span class="toc-text">流程控制语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%88%86%E7%B1%BB"><span class="toc-text">流程控制语句分类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%BA%E5%BA%8F%E7%BB%93%E6%9E%84"><span class="toc-text">顺序结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%B8%89%E7%A7%8D%E5%BD%A2%E5%BC%8F"><span class="toc-text">if 语句的三种形式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%81%9A%E4%B8%AA%E9%A2%98%E7%9B%AE"><span class="toc-text">做个题目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%B5%8C%E5%A5%97"><span class="toc-text">if 语句的嵌套</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%EF%BC%88%E6%9D%A1%E4%BB%B6%E5%88%86%E6%94%AF%E8%AF%AD%E5%8F%A5%EF%BC%89"><span class="toc-text">switch 语句（条件分支语句）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95%E6%A0%BC%E5%BC%8F"><span class="toc-text">语法格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-text">switch 语句的执行流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E7%BB%93%E6%9D%9F%E6%9D%A1%E4%BB%B6%E3%80%90%E9%9D%9E%E5%B8%B8%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">switch 语句的结束条件【非常重要】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#case-%E7%A9%BF%E9%80%8F"><span class="toc-text">case 穿透</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%AE%9E%E6%88%98%E4%B8%BE%E4%BE%8B%EF%BC%9A%E6%9B%BF%E6%8D%A2-if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">switch 语句的实战举例：替换 if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-1%EF%BC%88%E4%B8%8D%E6%8E%A8%E8%8D%90%E3%80%82%E8%BF%99%E7%A7%8D%E5%86%99%E6%B3%95%E5%A4%AA%E6%8C%AB%E4%BA%86%EF%BC%89"><span class="toc-text">写法 1（不推荐。这种写法太挫了）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-2%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E9%80%9A%E8%BF%87-return-%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%8C%E5%B0%86%E4%B8%8A%E9%9D%A2%E7%9A%84%E5%86%99%E6%B3%95%E8%BF%9B%E8%A1%8C%E6%94%B9%E8%BF%9B%EF%BC%89"><span class="toc-text">写法 2（推荐。通过 return 的方式，将上面的写法进行改进）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-3%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E5%B0%86-if-else-%E6%94%B9%E4%B8%BA-switch%EF%BC%89"><span class="toc-text">写法 3（推荐。将 if else 改为 switch）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95%EF%BC%9A%E9%80%82%E6%97%B6%E5%9C%B0%E5%8E%BB%E6%8E%89-break"><span class="toc-text">switch 语句的优雅写法：适时地去掉 break</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A1%A5%E5%85%85"><span class="toc-text">补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E5%92%8C-switch%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9"><span class="toc-text">if 和 switch如何选择</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8-return-%E4%BB%A3%E6%9B%BF-if-else"><span class="toc-text">用 return 代替 if else</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B5%9E%E8%B5%8F%E4%BD%9C%E8%80%85"><span class="toc-text">赞赏作者</span></a></li></ol>
      </div>
    </article>
  
  
  <article class="card card-content categories-widget">
    <div class="categories-card">
  <div class="categories-header">
    <i 
      class="iconfont icon-fenlei" 
      style="padding-right: 2px;">
    </i>分类
  </div>
  <div class="categories-list">
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/">
        <div class="categories-list-item">
          前端工具
          <span class="categories-list-item-badge">13</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          CSS基础
          <span class="categories-list-item-badge">18</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          CSS进阶
          <span class="categories-list-item-badge">9</span>
        </div>
      </a>
    
      <a href="/categories/HTML/">
        <div class="categories-list-item">
          HTML
          <span class="categories-list-item-badge">12</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          JS基础
          <span class="categories-list-item-badge">56</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80ES6/">
        <div class="categories-list-item">
          JS基础ES6
          <span class="categories-list-item-badge">10</span>
        </div>
      </a>
    
      <a href="/categories/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/">
        <div class="categories-list-item">
          JS基础异步
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/JS%E8%BF%9B%E9%98%B6/">
        <div class="categories-list-item">
          JS进阶
          <span class="categories-list-item-badge">11</span>
        </div>
      </a>
    
      <a href="/categories/%E7%A7%BB%E5%8A%A8web/">
        <div class="categories-list-item">
          移动web
          <span class="categories-list-item-badge">3</span>
        </div>
      </a>
    
      <a href="/categories/CSS%E5%92%8CDOM/">
        <div class="categories-list-item">
          CSS和DOM
          <span class="categories-list-item-badge">6</span>
        </div>
      </a>
    
      <a href="/categories/Node/">
        <div class="categories-list-item">
          Node
          <span class="categories-list-item-badge">16</span>
        </div>
      </a>
    
      <a href="/categories/Vue%E5%9F%BA%E7%A1%80/">
        <div class="categories-list-item">
          Vue基础
          <span class="categories-list-item-badge">15</span>
        </div>
      </a>
    
      <a href="/categories/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/">
        <div class="categories-list-item">
          性能优化
          <span class="categories-list-item-badge">7</span>
        </div>
      </a>
    
      <a href="/categories/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/">
        <div class="categories-list-item">
          前端工程化
          <span class="categories-list-item-badge">8</span>
        </div>
      </a>
    
  </div>
</div>
  </article>
  
  <article class="card card-content tags-widget">
    <div class="tags-card">
  <div class="tags-header">
    <i 
      class="iconfont icon-biaoqian" 
      style="padding-right: 2px;">
    </i>热门标签
  </div>
  <div class="tags-list">
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80/" 
        title="JS基础">
        <div class="tags-list-item">JS基础</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%9F%BA%E7%A1%80/" 
        title="CSS基础">
        <div class="tags-list-item">CSS基础</div>
      </a>
    
      <a 
        href="/tags/Node/" 
        title="Node">
        <div class="tags-list-item">Node</div>
      </a>
    
      <a 
        href="/tags/Vue%E5%9F%BA%E7%A1%80/" 
        title="Vue基础">
        <div class="tags-list-item">Vue基础</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E5%85%B7/" 
        title="前端工具">
        <div class="tags-list-item">前端工具</div>
      </a>
    
      <a 
        href="/tags/HTML/" 
        title="HTML">
        <div class="tags-list-item">HTML</div>
      </a>
    
      <a 
        href="/tags/JS%E8%BF%9B%E9%98%B6/" 
        title="JS进阶">
        <div class="tags-list-item">JS进阶</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80%E5%BC%82%E6%AD%A5/" 
        title="JS基础异步">
        <div class="tags-list-item">JS基础异步</div>
      </a>
    
      <a 
        href="/tags/JS%E5%9F%BA%E7%A1%80ES6/" 
        title="JS基础ES6">
        <div class="tags-list-item">JS基础ES6</div>
      </a>
    
      <a 
        href="/tags/CSS%E8%BF%9B%E9%98%B6/" 
        title="CSS进阶">
        <div class="tags-list-item">CSS进阶</div>
      </a>
    
      <a 
        href="/tags/%E5%89%8D%E7%AB%AF%E5%B7%A5%E7%A8%8B%E5%8C%96/" 
        title="前端工程化">
        <div class="tags-list-item">前端工程化</div>
      </a>
    
      <a 
        href="/tags/%E6%80%A7%E8%83%BD%E4%BC%98%E5%8C%96/" 
        title="性能优化">
        <div class="tags-list-item">性能优化</div>
      </a>
    
      <a 
        href="/tags/CSS%E5%92%8CDOM/" 
        title="CSS和DOM">
        <div class="tags-list-item">CSS和DOM</div>
      </a>
    
      <a 
        href="/tags/%E7%A7%BB%E5%8A%A8web/" 
        title="移动web">
        <div class="tags-list-item">移动web</div>
      </a>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
            <main class="main-column">
              
<article class="card card-content">
  <header>
    <h1 class="post-title">
      11-流程控制语句：选择结构（if和switch）
    </h1>
  </header>
  <div class="post-meta post-show-meta">
    <time datetime="2004-02-29T16:00:00.000Z">
      <i 
        class="iconfont icon-calendar" 
        style="margin-right: 2px;">
      </i>
      <span>2004-03-01</span>
    </time>
    
      <span class="dot"></span>
      
        <a 
          href="/categories/JS%E5%9F%BA%E7%A1%80/" 
          class="post-meta-link">
          JS基础
        </a>
      
    
    
      <span class="dot"></span>
      <span>3.6k 字</span>
    
  </div>
  
    <div 
      class="post-meta post-show-meta" 
      style="margin-top: -10px;">
      <div style="display: flex; align-items: center;">
        <i 
          class="iconfont icon-biaoqian" 
          style="margin-right: 2px; font-size: 1.15rem;">
        </i>
        
          
          <a 
            href="/tags/JS%E5%9F%BA%E7%A1%80/" 
            class="post-meta-link">
            JS基础
          </a>
        
      </div>
    </div>
  
  </header>
  <div 
    id="section" 
    class="post-content">
    <p><ArticleTopAd></ArticleTopAd></p>
<h2 id="代码块"><a href="#代码块" class="headerlink" title="代码块"></a>代码块</h2><p>用<code>&#123;&#125;</code>包围起来的代码，就是代码块。</p>
<p>在 ES5 语法中，代码块，只具有<strong>分组</strong>的作用，没有其他的用途。代码块中的内容，在外部是完全可见的。举例：</p>
<pre class="highlight"><span class="line">&#123;</span><br><span class="line">    <span class="keyword">var</span> a = <span class="number">2</span>;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;qianguyihao&#x27;</span>);</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;千古壹号&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;a = &#x27;</span> + a);</span><br></pre>

<p>打印结果：（可以看出，虽然变量 a 是定义在代码块中的，但是在外部依然可以访问）</p>
<pre class="highlight"><span class="line">千古壹号</span><br><span class="line">a = 2</span><br></pre>

<h2 id="流程控制语句"><a href="#流程控制语句" class="headerlink" title="流程控制语句"></a>流程控制语句</h2><p>在一个程序执行的过程中，各条语句的执行顺序对程序的结果是有直接影响的。所以，我们必须清楚每条语句的执行流程。而且，很多时候我们要通过控制语句的执行顺序来实现我们想要的业务逻辑和功能。</p>
<h3 id="流程控制语句分类"><a href="#流程控制语句分类" class="headerlink" title="流程控制语句分类"></a>流程控制语句分类</h3><ul>
<li><p>顺序结构</p>
</li>
<li><p>选择结构：if 语句、switch 语句</p>
</li>
<li><p>循环结构：while 语句、for 语句</p>
</li>
</ul>
<h2 id="顺序结构"><a href="#顺序结构" class="headerlink" title="顺序结构"></a>顺序结构</h2><p>按照代码的先后顺序，依次执行。结构图如下：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20181227_1200.png" class="lozad post-image"src="http://img.smyhvae.com/20181227_1200.png"></p>
<h2 id="if-语句"><a href="#if-语句" class="headerlink" title="if 语句"></a>if 语句</h2><p>if 语句有以下三种形式。</p>
<h3 id="if-语句的三种形式"><a href="#if-语句的三种形式" class="headerlink" title="if 语句的三种形式"></a>if 语句的三种形式</h3><p>形式1：（条件成立才执行。如果条件不成立，那就什么都不做）</p>
<pre class="highlight"><span class="line"><span class="keyword">if</span> (条件表达式) &#123;</span><br><span class="line">    <span class="comment">// 条件为真时，做的事情</span></span><br><span class="line">&#125;</span><br></pre>

<p>对于非布尔类型的数据，会先转换成布尔类型再判断。下同。</p>
<p>形式 2：</p>
<pre class="highlight"><span class="line"><span class="keyword">if</span> (条件表达式) &#123;</span><br><span class="line">    <span class="comment">// 条件为真时，做的事情</span></span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 条件为假时，做的事情</span></span><br><span class="line">&#125;</span><br></pre>

<p>形式3：（多分支的 if 语句）</p>
<pre class="highlight"><span class="line"><span class="keyword">if</span> (条件表达式<span class="number">1</span>) &#123;</span><br><span class="line">    <span class="comment">// 条件1为真时，做的事情</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (条件表达式<span class="number">2</span>) &#123;</span><br><span class="line">    <span class="comment">// 条件1不满足，条件2满足时，做的事情</span></span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (条件表达式<span class="number">3</span>) &#123;</span><br><span class="line">    <span class="comment">// 条件1、2不满足，条件3满足时，做的事情</span></span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 条件1、2、3都不满足时，做的事情</span></span><br><span class="line">&#125;</span><br></pre>

<p>以上所有的语句体中，只执行其中一个。</p>
<h3 id="做个题目"><a href="#做个题目" class="headerlink" title="做个题目"></a>做个题目</h3><pre class="highlight"><span class="line">根据BMI（身体质量指数）显示一个人的体型。</span><br><span class="line">BMI指数，就是体重、身高的一个计算公式。公式是：</span><br><span class="line">BMI =体重÷身高的平方</span><br><span class="line"></span><br><span class="line">比如，老师的体重是81.6公斤，身高是1.71米。</span><br><span class="line">那么老师的BMI就是  81.6 ÷ 1.712     等于 27.906022365856163</span><br><span class="line"></span><br><span class="line">过轻：低于18.5</span><br><span class="line">正常：18.5-24.99999999</span><br><span class="line">过重：25-27.9999999</span><br><span class="line">肥胖：28-32</span><br><span class="line">非常肥胖, 高于32</span><br><span class="line"></span><br><span class="line">用JavaScript开发一个程序，让用户先输入自己的体重，然后输入自己的身高（弹出两次prompt框）。</span><br><span class="line">计算它的BMI，根据上表，弹出用户的身体情况。比如“过轻” 、 “正常” 、“过重” 、 “肥胖” 、“非常肥胖”。</span><br></pre>

<p><strong>答案</strong>：</p>
<p>写法 1：</p>
<pre class="highlight"><span class="line"><span class="comment">//第一步，输入身高和体重</span></span><br><span class="line"><span class="keyword">const</span> height = <span class="built_in">parseFloat</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;请输入身高，单位是米&#x27;</span>));</span><br><span class="line"><span class="keyword">const</span> weight = <span class="built_in">parseFloat</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;请输入体重，单位是公斤&#x27;</span>));</span><br><span class="line"><span class="comment">//第二步，计算BMI指数</span></span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">BMI</span> = weight / <span class="title class_">Math</span>.<span class="title function_">pow</span>(height, <span class="number">2</span>);</span><br><span class="line"><span class="comment">//第三步，if语句来判断</span></span><br><span class="line"><span class="keyword">if</span> (<span class="variable constant_">BMI</span> &lt; <span class="number">18.5</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;偏瘦&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &lt; <span class="number">25</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;正常&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &lt; <span class="number">28</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;过重&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &lt;= <span class="number">32</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;肥胖&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;非常肥胖&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>写法 2：</p>
<pre class="highlight"><span class="line"><span class="comment">//第一步，输入身高和体重</span></span><br><span class="line"><span class="keyword">const</span> height = <span class="built_in">parseFloat</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;请输入身高，单位是米&#x27;</span>));</span><br><span class="line"><span class="keyword">const</span> weight = <span class="built_in">parseFloat</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;请输入体重，单位是公斤&#x27;</span>));</span><br><span class="line"><span class="comment">//第二步，计算BMI指数</span></span><br><span class="line"><span class="keyword">const</span> <span class="variable constant_">BMI</span> = weight / <span class="title class_">Math</span>.<span class="title function_">pow</span>(height, <span class="number">2</span>);</span><br><span class="line"><span class="comment">//第三步，if语句来判断</span></span><br><span class="line"><span class="keyword">if</span> (<span class="variable constant_">BMI</span> &gt; <span class="number">32</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;非常肥胖&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &gt;= <span class="number">28</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;肥胖&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &gt;= <span class="number">25</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;过重&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (<span class="variable constant_">BMI</span> &gt;= <span class="number">18.5</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;正常&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;偏瘦&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<h3 id="if-语句的嵌套"><a href="#if-语句的嵌套" class="headerlink" title="if 语句的嵌套"></a>if 语句的嵌套</h3><p>我们通过下面这个例子来引出 if 语句的嵌套。</p>
<pre class="highlight"><span class="line">一个加油站为了鼓励车主多加油，所以加的多有优惠。</span><br><span class="line">92号汽油，每升6元；如果大于等于20升，那么每升5.9；</span><br><span class="line">97号汽油，每升7元；如果大于等于30升，那么每升6.95</span><br><span class="line">编写JS程序，用户输入自己的汽油编号，然后输入自己加多少升，弹出价格。</span><br></pre>

<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20180117_2232.png" class="lozad post-image"src="http://img.smyhvae.com/20180117_2232.png"></p>
<p>代码实现如下：</p>
<pre class="highlight"><span class="line"><span class="comment">//第一步，输入</span></span><br><span class="line"><span class="keyword">const</span> bianhao = <span class="built_in">parseInt</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;您想加什么油？填写92或者97&#x27;</span>));</span><br><span class="line"><span class="keyword">const</span> sheng = <span class="built_in">parseFloat</span>(<span class="title function_">prompt</span>(<span class="string">&#x27;您想加多少升？&#x27;</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">//第二步，判断</span></span><br><span class="line"><span class="keyword">if</span> (bianhao == <span class="number">92</span>) &#123;</span><br><span class="line">    <span class="comment">//编号是92的时候做的事情</span></span><br><span class="line">    <span class="keyword">if</span> (sheng &gt;= <span class="number">20</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> price = sheng * <span class="number">5.9</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> price = sheng * <span class="number">6</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (bianhao == <span class="number">97</span>) &#123;</span><br><span class="line">    <span class="comment">//编号是97的时候做的事情</span></span><br><span class="line">    <span class="keyword">if</span> (sheng &gt;= <span class="number">30</span>) &#123;</span><br><span class="line">        <span class="keyword">const</span> price = sheng * <span class="number">6.95</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">const</span> price = sheng * <span class="number">7</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;不好意思，没有这个编号的汽油！&#x27;</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="title function_">alert</span>(<span class="string">&#x27;价格是&#x27;</span> + price);</span><br></pre>

<h2 id="switch-语句（条件分支语句）"><a href="#switch-语句（条件分支语句）" class="headerlink" title="switch 语句（条件分支语句）"></a>switch 语句（条件分支语句）</h2><p>switch 语句也叫条件分支语句。</p>
<h3 id="语法格式"><a href="#语法格式" class="headerlink" title="语法格式"></a>语法格式</h3><pre class="highlight"><span class="line"><span class="keyword">switch</span>(表达式) &#123;</span><br><span class="line">	<span class="keyword">case</span> 值<span class="number">1</span>：</span><br><span class="line">		语句体<span class="number">1</span>;</span><br><span class="line">		<span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">case</span> 值<span class="number">2</span>：</span><br><span class="line">		语句体<span class="number">2</span>;</span><br><span class="line">		<span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">	...</span><br><span class="line">	...</span><br><span class="line"></span><br><span class="line">	<span class="keyword">default</span>：</span><br><span class="line">		语句体 n+<span class="number">1</span>;</span><br><span class="line">		<span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p><strong>解释</strong>：switch 可以理解为“开关、转换” 。case 可以理解为“案例、选项”。</p>
<h3 id="switch-语句的执行流程"><a href="#switch-语句的执行流程" class="headerlink" title="switch 语句的执行流程"></a>switch 语句的执行流程</h3><p>流程图如下：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="http://img.smyhvae.com/20190815_1501.png" class="lozad post-image"src="http://img.smyhvae.com/20190815_1501.png"></p>
<p>执行流程如下：</p>
<p>（1）首先，计算出表达式的值，和各个 case 依次比较，一旦有对应的值，就会执行相应的语句，在执行的过程中，遇到 break 就会结束。</p>
<p>（2）然后，如果所有的 case 都和表达式的值不匹配，就会执行 default 语句体部分。</p>
<h3 id="switch-语句的结束条件【非常重要】"><a href="#switch-语句的结束条件【非常重要】" class="headerlink" title="switch 语句的结束条件【非常重要】"></a>switch 语句的结束条件【非常重要】</h3><ul>
<li>情况 a：遇到 break 就结束（而不是遇到 default 就结束）。因为 break 在此处的作用是，立即结束并退出整个 switch 语句。</li>
<li>情况 b：执行到程序的末尾就结束。</li>
</ul>
<p>我们稍后讲 case穿透的时候，你就会明白其中的奥妙了。</p>
<h3 id="注意点"><a href="#注意点" class="headerlink" title="注意点"></a>注意点</h3><p>1、switch 后面的括号里可以是变量、常量、表达式， 通常是一个<strong>变量</strong>（一般做法是：先把表达式存放到变量中）。</p>
<p>case 后面的值可以是变量、常量、表达式。</p>
<p>2、**case的判断逻辑是<code>===</code>，不是<code>==</code>**。因此，字符串<code>&#39;6&#39;</code>和 数字 <code>6</code> 是不一样的。</p>
<p>举例 1：</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> msg = <span class="string">&#x27;notice&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (msg) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;notice&#x27;</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;提示&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;warning&#x27;</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;警告&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&#x27;error&#x27;</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;错误&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;默认文案&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>举例 2：（case 后面的是表达式）</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> age = <span class="number">28</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (<span class="literal">true</span>) &#123;</span><br><span class="line">    <span class="keyword">case</span> age &lt; <span class="number">18</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;未成年人&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> age &gt;= <span class="number">18</span> &amp;&amp; age &lt;= <span class="number">65</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;还能干活儿&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> age &gt; <span class="number">65</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;该退休了&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;默认文案&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>上方代码解释：由于 switch 里的值是 true，所以，在众多的 case 语句中，会去匹配第一个符合 <code>case true</code>的语句，然后命中这条语句。</p>
<p>3、default不一定要写在最后面。 switch 中的 default 无论放到什么位置，都会等到所有case 都不匹配再执行。default 也可以省略。</p>
<h3 id="case-穿透"><a href="#case-穿透" class="headerlink" title="case 穿透"></a>case 穿透</h3><p>switch 语句中的<code>break</code>可以省略，但一般不建议（对于新手而言）。否则结果可能不是你想要的，会出现一个现象：<strong>case 穿透</strong>。</p>
<p>当然，如果你能利用好 case 穿透，会让代码写得十分优雅。</p>
<p><strong>举例 1</strong>：（case 穿透的情况）</p>
<pre class="highlight"><span class="line"><span class="keyword">const</span> num = <span class="number">4</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//switch判断语句</span></span><br><span class="line"><span class="keyword">switch</span> (num) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期一&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期二&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期三&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期四&#x27;</span>);</span><br><span class="line">    <span class="comment">//break;</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期五&#x27;</span>);</span><br><span class="line">    <span class="comment">//break;</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期六&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;星期日&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;你输入的数据有误&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>上方代码的运行结果，可能会令你感到意外：</p>
<pre class="highlight"><span class="line">星期四</span><br><span class="line">星期五</span><br><span class="line">星期六</span><br></pre>

<p>上方代码的解释：因为在 case 4 和 case 5 中都没有 break，那语句走到 case 6 的 break 才会停止。</p>
<p><strong>举例 2</strong>：</p>
<pre class="highlight"><span class="line"><span class="comment">//switch判断语句</span></span><br><span class="line"><span class="keyword">const</span> number = <span class="number">5</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (number) &#123;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;我是defaul语句&#x27;</span>);</span><br><span class="line">    <span class="comment">// break;</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;第二个呵呵:&#x27;</span> + number);</span><br><span class="line">    <span class="comment">//break;</span></span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;第三个呵呵:&#x27;</span> + number);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;第四个呵呵:&#x27;</span> + number);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>上方代码的运行结果，你也许会意外：</p>
<pre class="highlight"><span class="line">我是defaul语句</span><br><span class="line">第二个呵呵:5</span><br><span class="line">第三个呵呵:5</span><br></pre>

<p>上方代码的解释：代码走到 default 时，因为没有遇到 break，所以会继续往下走，直到遇见 break 或者走到程序的末尾。 从这个例子可以看出：switch 语句的结束与 default 的顺序无关。</p>
<h2 id="switch-语句的实战举例：替换-if-语句"><a href="#switch-语句的实战举例：替换-if-语句" class="headerlink" title="switch 语句的实战举例：替换 if 语句"></a>switch 语句的实战举例：替换 if 语句</h2><p>我们实战开发中，经常需要根据接口的返回码 retCode ，来让前端做不同的展示。</p>
<p>这种场景是业务开发中经常出现的，请一定要掌握。然而，很多人估计会这么写：</p>
<h3 id="写法-1（不推荐。这种写法太挫了）"><a href="#写法-1（不推荐。这种写法太挫了）" class="headerlink" title="写法 1（不推荐。这种写法太挫了）"></a>写法 1（不推荐。这种写法太挫了）</h3><pre class="highlight"><span class="line"><span class="keyword">let</span> retCode = <span class="number">1003</span>; <span class="comment">// 返回码 retCode 的值可能有很多种情况</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> (retCode == <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;接口联调成功&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">101</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;活动不存在&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">103</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;活动未开始&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">104</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;活动已结束&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">1001</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;参数错误&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">1002</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;接口频率限制&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">1003</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;未登录&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span> (retCode == <span class="number">1004</span>) &#123;</span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;（风控用户）提示 活动太火爆啦~军万马都在挤，请稍后再试&#x27;</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="comment">// 其他异常返回码</span></span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;系统君失联了，请稍候再试&#x27;</span>);</span><br><span class="line">&#125;</span><br></pre>

<p>如果你是按照上面的 <code>if else</code>的方式来写各种条件判断，说明你的代码水平太初级了，会被人喷的，千万不要这么写。这种写法，容易导致<strong>嵌套太深，可读性很差</strong>。</p>
<p>那要怎么改进呢？继续往下看。</p>
<h3 id="写法-2（推荐。通过-return-的方式，将上面的写法进行改进）"><a href="#写法-2（推荐。通过-return-的方式，将上面的写法进行改进）" class="headerlink" title="写法 2（推荐。通过 return 的方式，将上面的写法进行改进）"></a>写法 2（推荐。通过 return 的方式，将上面的写法进行改进）</h3><pre class="highlight"><span class="line"><span class="keyword">let</span> retCode = <span class="number">1003</span>; <span class="comment">// 返回码 retCode 的值可能有很多种情况</span></span><br><span class="line"><span class="title function_">handleRetCode</span>(retCode);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方法：根据接口不同的返回码，处理前端不同的显示状态</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">handleRetCode</span>(<span class="params">retCode</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;接口联调成功&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">101</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动不存在&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">103</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动未开始&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">104</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动已结束&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">1001</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;参数错误&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">1002</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;接口频率限制&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">1003</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;未登录&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (retCode == <span class="number">1004</span>) &#123;</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;（风控用户）提示 活动太火爆啦~军万马都在挤，请稍后再试&#x27;</span>);</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 其他异常返回码</span></span><br><span class="line">    <span class="title function_">alert</span>(<span class="string">&#x27;系统君失联了，请稍候再试&#x27;</span>);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>上面的写法 2，是比较推荐的写法：直接通过 return 的方式，让 function 里的代码不再继续往下走，这就达到目的了。对了，因为要用到 return ，所以整段代码是封装到一个 function 里的。</p>
<p>如果你以后看到有前端小白采用的是<strong>写法 1</strong>，请一定要把<strong>写法 2</strong>传授给他：不需要那么多的 if else，直接用 return 返回就行了。</p>
<h3 id="写法-3（推荐。将-if-else-改为-switch）"><a href="#写法-3（推荐。将-if-else-改为-switch）" class="headerlink" title="写法 3（推荐。将 if else 改为 switch）"></a>写法 3（推荐。将 if else 改为 switch）</h3><pre class="highlight"><span class="line"><span class="keyword">let</span> retCode = <span class="number">1003</span>; <span class="comment">// 返回码 retCode 的值可能有很多种情况</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (retCode) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">0</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;接口联调成功&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">101</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动不存在&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">103</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动未开始&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">104</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;活动已结束&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">1001</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;参数错误&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">1002</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;接口频率限制&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">1003</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;未登录&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">1004</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;（风控用户）提示 活动太火爆啦~军万马都在挤，请稍后再试&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 其他异常返回码</span></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="title function_">alert</span>(<span class="string">&#x27;系统君失联了，请稍候再试&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>在实战开发中，方式 3 是非常推荐的写法，甚至比方式 2 还要好。我们尽量不要写太多的 if 语句，避免代码嵌套过深。</p>
<h3 id="switch-语句的优雅写法：适时地去掉-break"><a href="#switch-语句的优雅写法：适时地去掉-break" class="headerlink" title="switch 语句的优雅写法：适时地去掉 break"></a>switch 语句的优雅写法：适时地去掉 break</h3><p>我们先来看看下面这段代码：（不推荐）</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> day = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (day) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;relax&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;relax&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line"></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br></pre>

<p>上面的代码，咋一看，好像没啥毛病。但你有没有发现，重复代码太多了？</p>
<p>实战开发中，凡是有重复的地方，我们都必须要想办法简化。写代码就是在不断重构的过程。</p>
<p>上面的代码，可以改进如下：（推荐，非常优雅）</p>
<pre class="highlight"><span class="line"><span class="keyword">let</span> day = <span class="number">2</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (day) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="number">1</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">2</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">3</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">4</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">5</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;work&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>; <span class="comment">// 在这里放一个 break</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">case</span> <span class="number">6</span>:</span><br><span class="line">    <span class="keyword">case</span> <span class="number">7</span>:</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;relax&#x27;</span>);</span><br><span class="line">        <span class="keyword">break</span>; <span class="comment">// 在这里放一个 break</span></span><br><span class="line"></span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br></pre>

<p>你没看错，就是上面的这种写法，能达到同样的效果，非常优雅。</p>
<p>小白可能认为这样的写法可读性不强，所以说他是小白。我可以明确告诉你，改进后的这种写法，才是最优雅的、最简洁、可读性最好的。</p>
<h2 id="补充"><a href="#补充" class="headerlink" title="补充"></a>补充</h2><h3 id="if-和-switch如何选择"><a href="#if-和-switch如何选择" class="headerlink" title="if 和 switch如何选择"></a>if 和 switch如何选择</h3><p>如果是对区间进行判断，则建议用 if。如果是对几个固定的值进行判断，那么，数量少的话用 if，数量多的话用switch。</p>
<h3 id="用-return-代替-if-else"><a href="#用-return-代替-if-else" class="headerlink" title="用 return 代替 if else"></a>用 return 代替 if else</h3><p>业务场景举例：</p>
<p>我们在实战业务中涉及到调接口时，一般会这样做：</p>
<ul>
<li><p>接口返回码为 0 时，前端 resolve。</p>
</li>
<li><p>接口返回未登录时，前端跳转到登录页面。</p>
</li>
<li><p>接口返回其他情况，或者无返回时，前端 reject。</p>
</li>
</ul>
<p>写法 1、if else 的写法：（不推荐）</p>
<pre class="highlight"><span class="line"><span class="keyword">if</span> (res) &#123;</span><br><span class="line">    <span class="keyword">if</span> (+res.<span class="property">retCode</span> == <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="title function_">resolve</span>(res);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (+res.<span class="property">retCode</span> == <span class="number">8888</span>) &#123;</span><br><span class="line">        <span class="title function_">goLogin</span>();</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="title function_">reject</span>(res);</span><br><span class="line">    &#125;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="title function_">reject</span>();</span><br><span class="line">&#125;</span><br></pre>

<p>写法 2、 return 的写法：（推荐）</p>
<pre class="highlight"><span class="line"><span class="keyword">if</span> (!res || +res.<span class="property">retCode</span> !== <span class="number">0</span>) &#123;</span><br><span class="line">    <span class="keyword">if</span> (+res.<span class="property">retCode</span> === <span class="number">8888</span>) &#123;</span><br><span class="line">        <span class="comment">// 未登录</span></span><br><span class="line">        <span class="title function_">goLogin</span>();</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="title function_">reject</span>(res);</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="title function_">resolve</span>(res);</span><br></pre>

<p>备注：如果你没学过 Promise，这个例子可以先不看。等以后学了 Promise 再回来看就很容易明白了。</p>
<h2 id="赞赏作者"><a href="#赞赏作者" class="headerlink" title="赞赏作者"></a>赞赏作者</h2><p>创作不易，你的赞赏和认可，是我更新的最大动力：</p>
<p><img  srcset="data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%20300%20300'%3E%3C/svg%3E" data-src="https://img.smyhvae.com/20220401_1800.jpg" class="lozad post-image"src="https://img.smyhvae.com/20220401_1800.jpg"></p>

  </div>
  <div>
    
      <div 
        class="post-note note-warning copyright" 
        style="margin-top: 42px">
        <p>
          <span style="font-weight: bold;">作者：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="/about">
            zwl5670
          </a>
        </p>
        <p>
          <span style="font-weight: bold;">文章链接：</span><a 
            target="_blank" 
            rel="nofollow noopener noreferrer" 
            href="https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/11-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%EF%BC%9A%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84%EF%BC%88if%E5%92%8Cswitch%EF%BC%89/">
            https://zwl5670.gitee.io/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/11-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%EF%BC%9A%E9%80%89%E6%8B%A9%E7%BB%93%E6%9E%84%EF%BC%88if%E5%92%8Cswitch%EF%BC%89/
          </a>
        </p>
        <p><span style="font-weight: bold;">版权声明：</span>本博客所有文章除特别声明外，均采用<a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/deed.zh">CC BY-NC-SA 4.0 协议</a>。转载请注明出处！</p>
      </div>
    
  </div>
</article>
<div class="nav">
  
    <div class="nav-item-prev">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/12-%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%EF%BC%9A%E5%BE%AA%E7%8E%AF%E7%BB%93%E6%9E%84%EF%BC%88for%E5%92%8Cwhile%EF%BC%89/" 
        class="nav-link">
        <i class="iconfont icon-left nav-prev-icon"></i>
        <div>
          <div class="nav-label">上一篇</div>
          
            <div class="nav-title">12-流程控制语句：循环结构（for和while） </div>
          
        </div>
      </a>
    </div>
  
  
    <div class="nav-item-next">
      <a 
        href="/2004/03/01/04-JavaScript%E5%9F%BA%E7%A1%80/10-%E8%BF%90%E7%AE%97%E7%AC%A6/" 
        class="nav-link">
        <div>
          <div class="nav-label">下一篇</div>
          
            <div class="nav-title">10-运算符 </div>
          
        </div>
        <i class="iconfont icon-right nav-next-icon"></i>
      </a>
    </div>
  
</div>

<div 
  class="card card-content toc-card" 
  id="mobiletoc">
  <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-text">代码块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5"><span class="toc-text">流程控制语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%88%86%E7%B1%BB"><span class="toc-text">流程控制语句分类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%BA%E5%BA%8F%E7%BB%93%E6%9E%84"><span class="toc-text">顺序结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%B8%89%E7%A7%8D%E5%BD%A2%E5%BC%8F"><span class="toc-text">if 语句的三种形式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%81%9A%E4%B8%AA%E9%A2%98%E7%9B%AE"><span class="toc-text">做个题目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%B5%8C%E5%A5%97"><span class="toc-text">if 语句的嵌套</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%EF%BC%88%E6%9D%A1%E4%BB%B6%E5%88%86%E6%94%AF%E8%AF%AD%E5%8F%A5%EF%BC%89"><span class="toc-text">switch 语句（条件分支语句）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95%E6%A0%BC%E5%BC%8F"><span class="toc-text">语法格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-text">switch 语句的执行流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E7%BB%93%E6%9D%9F%E6%9D%A1%E4%BB%B6%E3%80%90%E9%9D%9E%E5%B8%B8%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">switch 语句的结束条件【非常重要】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#case-%E7%A9%BF%E9%80%8F"><span class="toc-text">case 穿透</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%AE%9E%E6%88%98%E4%B8%BE%E4%BE%8B%EF%BC%9A%E6%9B%BF%E6%8D%A2-if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">switch 语句的实战举例：替换 if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-1%EF%BC%88%E4%B8%8D%E6%8E%A8%E8%8D%90%E3%80%82%E8%BF%99%E7%A7%8D%E5%86%99%E6%B3%95%E5%A4%AA%E6%8C%AB%E4%BA%86%EF%BC%89"><span class="toc-text">写法 1（不推荐。这种写法太挫了）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-2%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E9%80%9A%E8%BF%87-return-%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%8C%E5%B0%86%E4%B8%8A%E9%9D%A2%E7%9A%84%E5%86%99%E6%B3%95%E8%BF%9B%E8%A1%8C%E6%94%B9%E8%BF%9B%EF%BC%89"><span class="toc-text">写法 2（推荐。通过 return 的方式，将上面的写法进行改进）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-3%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E5%B0%86-if-else-%E6%94%B9%E4%B8%BA-switch%EF%BC%89"><span class="toc-text">写法 3（推荐。将 if else 改为 switch）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95%EF%BC%9A%E9%80%82%E6%97%B6%E5%9C%B0%E5%8E%BB%E6%8E%89-break"><span class="toc-text">switch 语句的优雅写法：适时地去掉 break</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A1%A5%E5%85%85"><span class="toc-text">补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E5%92%8C-switch%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9"><span class="toc-text">if 和 switch如何选择</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8-return-%E4%BB%A3%E6%9B%BF-if-else"><span class="toc-text">用 return 代替 if else</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B5%9E%E8%B5%8F%E4%BD%9C%E8%80%85"><span class="toc-text">赞赏作者</span></a></li></ol>
</div>
            </main>
            <aside class="right-column">
              <div class="sticky-widescreen">
  
  
    <article class="card card-content toc-card">
      <div class="toc-header">
  <i 
    class="iconfont icon-menu" 
    style="padding-right: 2px;">
  </i>目录
</div>
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BB%A3%E7%A0%81%E5%9D%97"><span class="toc-text">代码块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5"><span class="toc-text">流程控制语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B5%81%E7%A8%8B%E6%8E%A7%E5%88%B6%E8%AF%AD%E5%8F%A5%E5%88%86%E7%B1%BB"><span class="toc-text">流程控制语句分类</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E9%A1%BA%E5%BA%8F%E7%BB%93%E6%9E%84"><span class="toc-text">顺序结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%B8%89%E7%A7%8D%E5%BD%A2%E5%BC%8F"><span class="toc-text">if 语句的三种形式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%81%9A%E4%B8%AA%E9%A2%98%E7%9B%AE"><span class="toc-text">做个题目</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%B5%8C%E5%A5%97"><span class="toc-text">if 语句的嵌套</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%EF%BC%88%E6%9D%A1%E4%BB%B6%E5%88%86%E6%94%AF%E8%AF%AD%E5%8F%A5%EF%BC%89"><span class="toc-text">switch 语句（条件分支语句）</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%AF%AD%E6%B3%95%E6%A0%BC%E5%BC%8F"><span class="toc-text">语法格式</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E6%89%A7%E8%A1%8C%E6%B5%81%E7%A8%8B"><span class="toc-text">switch 语句的执行流程</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E7%BB%93%E6%9D%9F%E6%9D%A1%E4%BB%B6%E3%80%90%E9%9D%9E%E5%B8%B8%E9%87%8D%E8%A6%81%E3%80%91"><span class="toc-text">switch 语句的结束条件【非常重要】</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%B3%A8%E6%84%8F%E7%82%B9"><span class="toc-text">注意点</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#case-%E7%A9%BF%E9%80%8F"><span class="toc-text">case 穿透</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E5%AE%9E%E6%88%98%E4%B8%BE%E4%BE%8B%EF%BC%9A%E6%9B%BF%E6%8D%A2-if-%E8%AF%AD%E5%8F%A5"><span class="toc-text">switch 语句的实战举例：替换 if 语句</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-1%EF%BC%88%E4%B8%8D%E6%8E%A8%E8%8D%90%E3%80%82%E8%BF%99%E7%A7%8D%E5%86%99%E6%B3%95%E5%A4%AA%E6%8C%AB%E4%BA%86%EF%BC%89"><span class="toc-text">写法 1（不推荐。这种写法太挫了）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-2%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E9%80%9A%E8%BF%87-return-%E7%9A%84%E6%96%B9%E5%BC%8F%EF%BC%8C%E5%B0%86%E4%B8%8A%E9%9D%A2%E7%9A%84%E5%86%99%E6%B3%95%E8%BF%9B%E8%A1%8C%E6%94%B9%E8%BF%9B%EF%BC%89"><span class="toc-text">写法 2（推荐。通过 return 的方式，将上面的写法进行改进）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%86%99%E6%B3%95-3%EF%BC%88%E6%8E%A8%E8%8D%90%E3%80%82%E5%B0%86-if-else-%E6%94%B9%E4%B8%BA-switch%EF%BC%89"><span class="toc-text">写法 3（推荐。将 if else 改为 switch）</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#switch-%E8%AF%AD%E5%8F%A5%E7%9A%84%E4%BC%98%E9%9B%85%E5%86%99%E6%B3%95%EF%BC%9A%E9%80%82%E6%97%B6%E5%9C%B0%E5%8E%BB%E6%8E%89-break"><span class="toc-text">switch 语句的优雅写法：适时地去掉 break</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%A1%A5%E5%85%85"><span class="toc-text">补充</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#if-%E5%92%8C-switch%E5%A6%82%E4%BD%95%E9%80%89%E6%8B%A9"><span class="toc-text">if 和 switch如何选择</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%94%A8-return-%E4%BB%A3%E6%9B%BF-if-else"><span class="toc-text">用 return 代替 if else</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E8%B5%9E%E8%B5%8F%E4%BD%9C%E8%80%85"><span class="toc-text">赞赏作者</span></a></li></ol>
    </article>
  
  
  <article class="card card-content">
    <div class="recent-posts-card">
  <div class="recent-posts-header">
    <i 
      class="iconfont icon-wenzhang_huaban" 
      style="padding-right: 2px;">
    </i>最近文章
  </div>
  <div class="recent-posts-list">
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/11-React%20Navive%E5%88%9D%E8%AF%86/"><div class="recent-posts-item-content">11-React Navive初识</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/10-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E4%BD%BF%E7%94%A8customRequest%E6%96%B9%E6%B3%95%E8%87%AA%E5%AE%9A%E4%B9%89%E4%B8%8A%E4%BC%A0%E8%A1%8C%E4%B8%BA/"><div class="recent-posts-item-content">10-AntD框架的upload组件上传图片时使用customRequest方法自定义上传行为</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/09-AntD%E6%A1%86%E6%9E%B6%E7%9A%84upload%E7%BB%84%E4%BB%B6%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E6%97%B6%E9%81%87%E5%88%B0%E7%9A%84%E4%B8%80%E4%BA%9B%E5%9D%91/"><div class="recent-posts-item-content">09-AntD框架的upload组件上传图片时遇到的一些坑</div></a>
      </div>
    
      <div class="recent-posts-item">
        <div class="recent-posts-item-title">2023-03-09</div>
        <a href="/2023/03/09/13-React%E5%9F%BA%E7%A1%80/08-Ant%20Design%E7%9A%84%E5%9F%BA%E6%9C%AC%E4%BD%BF%E7%94%A8/"><div class="recent-posts-item-content">08-Ant Design的基本使用</div></a>
      </div>
    
  </div>
</div>
  </article>
  
  
</div>
            </aside>
          </div>
        </div>
      </div>
    </div>
     
    <footer class="footer">
  <div class="footer-container">
    <div>
      <div class="footer-dsc">
        <span>
          Copyright ©
          
            2023
          
          
        </span>
        &nbsp;
        <a 
          href="/" 
          class="footer-link">
          前端面试
        </a>
      </div>
    </div>

    
      <div class="footer-dsc">
        
          Powered by
          <a 
            href="https://hexo.io/" 
            class="footer-link" 
            target="_blank" 
            rel="nofollow noopener noreferrer">
            &nbsp;Hexo
          </a>
        
        
          <span>&nbsp;|&nbsp;</span>
        
        
          Theme -
          <a 
            href="https://github.com/theme-kaze" 
            class="footer-link" 
            target="_blank"
            rel="nofollow noopener noreferrer">
            &nbsp;Kaze
          </a>
        
      </div>
    
    
    
    
</footer>
 
    
  <a 
    role="button" 
    id="scrollbutton" 
    class="basebutton" 
    aria-label="回到顶部">
    <i class="iconfont icon-arrowleft button-icon"></i>
  </a>

<a 
  role="button" 
  id="menubutton"
  aria-label="menu button"
  class="basebutton">
  <i class="iconfont icon-menu button-icon"></i>
</a>
<a 
  role="button" 
  id="popbutton" 
  class="basebutton" 
  aria-label="控制中心">
  <i class="iconfont icon-expand button-icon"></i>
</a>
<a 
  role="button" 
  id="darkbutton" 
  class="basebutton darkwidget" 
  aria-label="夜色模式">
  <i class="iconfont icon-weather button-icon"></i>
</a>
<a 
  role="button" 
  id="searchbutton" 
  class="basebutton searchwidget" 
  aria-label="搜索">
  <i class="iconfont icon-search button-icon"></i>
</a> 
     
     
     
      <script>
  var addImgLayout = function () {
    var img = document.querySelectorAll('.post-content img')
    var i
    for (i = 0; i < img.length; i++) {
      var wrapper = document.createElement('a')
      wrapper.setAttribute('href', img[i].getAttribute('data-src'))
      wrapper.setAttribute('aria-label', 'illustration')
      wrapper.style.cssText =
        'width: 100%; display: flex; justify-content: center;'
      if (img[i].alt) wrapper.dataset.caption = img[i].alt
      wrapper.dataset.nolink = true
      img[i].before(wrapper)
      wrapper.append(img[i])
      var divWrap = document.createElement('div')
      divWrap.classList.add('gallery')
      wrapper.before(divWrap)
      divWrap.append(wrapper)
    }
    baguetteBox.run('.gallery')
  }
</script>
<script>
  loadScript(
    "/js/lib/lightbox/baguetteBox.min.js",
    addImgLayout
  )
</script>
 
     
     
    <script src="/js/main.js"></script> 
     
    
      <script>
        var addLazyload = function () {
          var observer = lozad('.lozad', {
            load: function (el) {
              el.srcset = el.getAttribute('data-src')
            },
            loaded: function (el) {
              el.classList.add('loaded')
            },
          })
          observer.observe()
        }
      </script>
      <script>
        loadScript('/js/lib/lozad.min.js', addLazyload)
      </script>
    
    <script src="//instant.page/5.1.0" type="module"
      integrity="sha384-by67kQnR+pyfy8yWP4kPO12fHKRLHZPfEsiSXR8u2IKcTdxD805MGUXBzVPnkLHw"></script>
    
    
  </body>
</html>
